#!/usr/bin/env python
# -*- coding: utf-8 -*-
#===============================================================================
# Copyright 2011 zod.yslin
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# 
# Author: zod.yslin
# Email: 
# File Name: polymorphism.py
# Description: 
#   多型 (polymorphism) 是物件導向程式語言 (object-oriented programming language) 
#   的一項主要特性，使物件 (object) 的使用更具彈性。
#   簡單來說，多型可使物件的型態具有通用的效力
#  
#   多型的應用很多，例如串列中可接受不同型態的物件當元素，或是方法可用不同型態的參數等
# Edit History: 
#   2011-08-12    File created.
#===============================================================================
class Demo(object):
    def __init__(self, i):
        self.i = i
     
    def __str__(self):
        return str(self.i)
          
    def hello(self):
        print "Demo" , self.i
        print("hello " + self.__str__())
 
class SubDemo1(Demo):
    def __init__(self, i, j):
        super(SubDemo1, self).__init__(i)
        self.j = j
     
    def __str__(self):
        return super(SubDemo1, self).__str__() + str(self.j)
 
class SubDemo2(Demo):
    def __init__(self, i, j):
        super(SubDemo2, self).__init__(i)
        self.j = j
        self.k = str(self.i) + str(self.j)
     
    def __str__(self):
        print "SubDemo2" , self.k
        return self.k
 
# SubDemo1 與 SubDemo2 繼承 (inherit) 自 Demo ，因此兩個子類別也都繼承了 hello() 方法 (method) ，
# 雖然 SubDemo1 與 SubDemo2 所建立的物件各自是不同型態，然而由繼承關係兩種型態可通用 hello() 
a = SubDemo1(22, 33)
b = SubDemo2(44, "55")
#print SubDemo2.__mro__
a.hello()
b.hello()

# d1 為字串 (string) ， d2 為串列 (list) ，兩者皆屬於序列 (sequence) 的複合資料型態 
# (compound data type) ，有通用的 count() 方法，可計算某元素 (element) 累計出現的次數。
d1 = "12345"
d2 = [1, 2, 3, 4, "5"]  
print(d1.count("4"))
print(d2.count("4"))


